<template>
  <div v-page-show="{ show: operate.checkedProject, text: `请选择项目后查看` }">
    <RePage>
      <div class="split-pane">
        <splitpane :splitSet="settingLR">
          <template #paneL>
            <!-- <div class="flex w-[100%] gap-[20px]">
            <div class="w-[200px] bg-[red] h-[100px]" v-for="item in 4" :key="item"></div>
          </div> -->
            <div class="pr-[16px] h-full">
              <treeList ref="treeListRef" :treeProops="treeProops" :treeEvents="treeEvents" :pageShow="false"
                :inputShow="false" />
            </div>
          </template>

          <template #paneR>
            <div class="pl-[20px]">
              <div>
                <el-button v-auth="'business.project-drawing.create'" type="primary" :icon="Plus"
                  @click="add">添加</el-button>
                <el-button v-auth="'business.project-drawing.upload'" type="primary"
                  @click="importCardInfo" plain>上传图纸</el-button>
                <el-button type="danger" :icon="Delete" :disabled="!selectionData.length"
                  @click="deletes()">批量删除</el-button>
              </div>

              <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
                @selection-change="selectionChange" :isShowPag="false">

                <template #showMode="{ row }">
                  <!-- {{ isNullOrEmpty( row ) }} -->
                  <el-text>{{ isNullOrEmpty( SHOWMODE_TYPE[row.showMode]?.label ) }}</el-text>
                </template>
                <template #sort="{ row }">
                  <el-space>
                    <sj-link custom-type="sblue" :underline="false" @click="upDown(1, row)">上移</sj-link>
                    <sj-link custom-type="sblue" :underline="false" @click="upDown(2, row)">下移</sj-link>
                  </el-space>
                </template>

                <template #action="{ row }">
                  <el-space>
                    <!-- <sj-link custom-type="sblue" :underline="false" @click="info(row)">查看</sj-link> -->
                    <sj-link v-auth="'business.project-drawing.update'" custom-type="sblue" :underline="false"
                      @click="edit(row)">编辑</sj-link>
                    <sj-link v-auth="'business.project-drawing.remove'" custom-type="sred" :underline="false"
                      @click="deletes(row)">删除</sj-link>
                  </el-space>
                </template>
              </pure-table>
              <div class="mt-5">
                <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
                  :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList"
                  @current-change="getTableList" />
              </div>
            </div>
          </template>
        </splitpane>
      </div>

    </RePage>
  </div>

</template>
<script lang="ts" setup>
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'
import treeList from '@/components/treeList/treeList.vue'
import splitpane, { ContextProps } from "@/components/ReSplitPane";

import RePage from "@/components/RePage/index.vue";
import { SHOWMODE_TYPE } from '@/constant/drawing-management';
import editForm from "./form.vue";
import infos from "./info.vue";
import importCards from "./update.vue";
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, getInfo, addInfo, editInfo, deleteInfo, importFlowCard, darwTreeList, darwUpDown, importdraw } from '@/api/operate/project-management/project-management/drawing-management/index';
import { titles, defaultSearchForm, prompt, defaultInfoForm } from './index';
import { addDialog } from "@/components/ReDialog";
import { deviceDetection, debounce } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customPromiseDebounce } from "@/utils/functions";

import { usePageVariablesStoreHook, UNIT_TYPE_VIEW_Map } from '@/store/modules/pageVariables'
const operate = usePageVariablesStoreHook().getOperate()
console.log('operate', operate);
// const searchForm = ref(defaultSearchForm());
const searchFrom = ref(defaultSearchForm());
const settingLR: ContextProps = reactive({
  minPercent: 17,
  maxPercent: 17,
  defaultPercent: 17,
  split: "vertical"
});
const props = {
  label: "buildingName",
  value: "buildingId"
  // children: "children",
  // isLeaf: "isLeaf"
};
const projectList = ref([]);
const isLoading = ref(true)
const checkedProject = ref(0);
const checkedUnitId = ref(null);
const treeRef = ref();
const treeListRef = ref()
//树状图
//获取数据

const loadProjectList = () => {
  return new Promise((resolve, reject) => {
    isLoading.value = true;
    darwTreeList()
      .then(res => {
        projectList.value = res.result
        console.log(projectList.value, "项目列表");
      })
      .finally(() => {
        isLoading.value = false;
        resolve('');
      });
  });
};
const handleNodeClick = data => {
  console.log(data, "点击事件");
  searchFrom.value.buildingId = data.buildingId;
  getTableList()

};
const handleCheckChange = (data, isChecked) => {



};
const treeProops = ref({
  props: props,
  data: projectList,
  nodeKey: "value",
  'item-size': 46,
  'highlight-current': true

});
const treeEvents = {
  nodeClick: handleNodeClick,
  checkChange: handleCheckChange
};

const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0,
});

const searchFormRules = [
  {
    type: 'input', field: 'VR', title: titles.VR, value: null, props: {
      placeholder: prompt.VR, clearable: true
    }
  },
  {
    type: 'input', field: 'isDefault', title: titles.isDefault, value: null, props: {
      placeholder: prompt.isDefault, clearable: true
    }
  },
  {
    type: 'input', field: 'TopId', title: titles.TopId, value: null, props: {
      placeholder: prompt.TopId, clearable: true
    }
  },
  {
    type: 'input', field: 'showMode', title: titles.showMode, value: null, props: {
      placeholder: prompt.showMode, clearable: true
    }
  },
  {
    type: 'input', field: 'drawingName', title: titles.drawingName, value: null, props: {
      placeholder: prompt.drawingName, clearable: true
    }
  },
  {
    type: 'input', field: 'projectId', title: titles.projectId, value: null, props: {
      placeholder: prompt.projectId, clearable: true
    }
  },
  {
    type: 'input', field: 'buildingId', title: titles.buildingId, value: null, props: {
      placeholder: prompt.buildingId, clearable: true
    }
  },
  {
    type: 'input', field: 'img', title: titles.img, value: null, props: {
      placeholder: prompt.img, clearable: true
    }
  },
  {
    type: 'input', field: 'id', title: titles.id, value: null, props: {
      placeholder: prompt.id, clearable: true
    }
  },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];
const selectionData = ref([]);
const roleTableConfig = [
  { type: "selection", align: "left" },
  { prop: 'id', label: titles.id, width:  100, fixed: 'left' },
  { prop: 'drawingName', label: titles.drawingName, minWidth: 150 },
  { slot: 'showMode', label: titles.showMode, minWidth: 100 },
  { slot: 'sort', label: '排序', minWidth: 100 },

  { slot: 'action', label: titles.action, width: 100, fixed: 'right' },
];
onMounted(() => {
  loadProjectList().then(() => {
    treeListRef.value.getTreeRef().setCurrentKey(projectList.value[0].buildingId);
    searchFrom.value.buildingId = projectList.value[0].buildingId
    getTableList()
  })


});
// 获取列表数据
const getTableList = () => {
  getList(searchFrom.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}
//上移下移
const upDown = (e, item) => {
  console.log('item', item);

  darwUpDown({
    id: item.id,
    op: e
  }).then(res => {
    getTableList()
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchFrom.value, defaultSearchForm())
  key.value++
  getTableList()
}
// 详情
const info = (row) => {
  addDialog({
    title: `详情`,
    hideFooter: true,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        formInline: defaultInfoForm()
      }
      getInfo({ id: row.id }).then(res => {
        if (res.code == 200) {
          showInfo.value = res.result
          options.props.formInline = res.result
        }
      }).finally(() => {
        options.props.isLoading = false
      })
    },
  });
}
// 新增
const add = (row) => {
  showInfo.value = {}
  openDialog()
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑图纸", row)
}
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids: row ? [row.id] : selectionData.value.map(item => item.id) }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
// 开启弹窗
const openDialog = (title = "添加图纸", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoForm()
        }
        getInfo({ id: row.id }).then(res => {

          if (res.code == 200) {
            showInfo.value = res.result
            options.props.formInline = res.result


          }
        }).finally(() => {
          options.props.isLoading = false
        })
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoForm()
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      formData.buildingId = searchFrom.value.buildingId
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加图纸") {
            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
const selectionChange = data => {
  selectionData.value = data;
};
const importCardInfo = () => {
  addDialog({
    title: `文件导入`,
    width: "800px",
    draggable: true,
    props: {
      importForm: {
        file: null
      }
    },
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(importCards, { ref: formRef }),
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);

          // 表单规则校验通过
          options.props.isLoading = true;
          let formData = new FormData();
          // formData.append("file", options.props.importForm.file)
          const files = options.props.importForm.file
          for (let key in files) {
            formData.append(`file[${parseInt(key)}]`, files[key]);
          }



          DebounceImportFlowCard(formData).then(res => {
            if (res.code == 200) {
              console.log('集合', res);

              importdraw({
                drawingNames: res.result.drawingNames,
                paths: res.result.paths,
                buildingId: searchFrom.value.buildingId
              }).then(res => {
                console.log("成功");
                chores();
              })

            }
            options.props.isLoading = false;
          }).catch((err) => {
            if (err !== '请求中') {
              options.props.isLoading = false;
            }
          })
        }
      })
    }
  });
}
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
const DebounceImportFlowCard = customPromiseDebounce(importFlowCard, 1000, true);
</script>
<style lang="scss" scoped>
.split-pane {
  width: 100%;
  height: calc(100vh - 200px);
  //   font-size: 50px;
  //   text-align: center;
  //   border: 1px solid #e5e6eb;

  //   .dv-a {
  //     padding-top: 0vh;
  //     color: rgba($color: dodgerblue, $alpha: 80%);
  //   }

  //   .dv-b {
  //     padding-top: 0vh;
  //     color: rgba($color: #000, $alpha: 80%);
  //   }

  //   .dv-c {
  //     padding-top: 0vh;
  //     color: rgba($color: #ce272d, $alpha: 80%);
  //   }
}
</style>
